package com.ledim.activity;

import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;
import com.igexin.sdk.PushManager;
import com.ledim.activity.base.LeDimBaseActivity;
import com.ledim.bean.RoomInfoResponse;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.ledim.fragment.LedimChoiceFragment;
import com.ledim.fragment.LedimProfileFragment;
import com.ledim.fragment.LedimRoomFragment;
import com.ledim.service.ApiService;
import com.ledim.service.LedimApiServiceFactory;
import com.ledim.utils.LedimSpUtils;
import com.ledim.utils.LogUtil;
import com.ledim.utils.ToastUtil;
import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.core.bean.IVideo;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class MainActivity extends LeDimBaseActivity {

    private static final int FLAG_TAB_ONE = 1;
    private static final int FLAG_TAB_TWO = 2;
    private static final int FLAG_TAB_THREE = 3;

    private LedimChoiceFragment mChoiceFragment;
    private LedimRoomFragment mLedimRoomFragment;
    private LedimProfileFragment mLedimProfileFragment;

    private LinearLayout mChoice;
    private LinearLayout mRoom;
    private LinearLayout mProfile;

    private FragmentManager mFragmentManager;
    private FragmentTransaction mTransaction;
    private int preTabIndex;
    // MainActivity 实体
    private static MainActivity instance;
    private long lastTime;

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onResume() {
        super.onResume();
        LogUtil.e("ccx onresum");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LetvSDK.getInstance().init();
        getWindow().setBackgroundDrawable(null);
        //        //开始百度定位
        //        LocationUtil.getInstance(this).initLocation();

        Uri uri = getIntent().getData();
        if (uri != null) {
            String link = uri.toString();
            getUserRoomInfo(link.replace("intent://com.letv.android.young.client/rooms/", ""));
        }
        initView();
        LeDimAnalysisUtils.reportEvent("launch");
        //初始化个推SDK
        if (LedimSpUtils.getPushMsg()) {
            PushManager.getInstance().initialize(getApplicationContext());
        }
        instance = this;
    }

    public static MainActivity getInstance() {
        return instance;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    public void getUserRoomInfo(String roomId) {
        LedimApiServiceFactory.createService(ApiService.class)
                              .getLedimRoomInfo(roomId)
                              .observeOn(AndroidSchedulers.mainThread())
                              .subscribeOn(Schedulers.io())
                              .subscribe(new Observer<RoomInfoResponse>() {
                                  @Override
                                  public void onCompleted() {

                                  }

                                  @Override
                                  public void onError(Throwable e) {
                                      LogUtil.e("onError--" + e.getMessage());
                                  }

                                  @Override
                                  public void onNext(RoomInfoResponse response) {
                                      LogUtil.e("ccx -- " + response.toString());
                                      if (response.success) {
                                          IVideo roomVideo = new IVideo();
                                          roomVideo.setmVid(0);
                                          if (response.data.roomId.equals(LedimSpUtils.getUid())) {
                                              LetvSDK.getInstance()
                                                     .playRoom(MainActivity.this, roomVideo, response.data, true, false);
                                          } else {
                                              LetvSDK.getInstance()
                                                     .playRoom(MainActivity.this, roomVideo, response.data);
                                          }
                                      }

                                  }

                              });
    }

    /**
     * 返回键退出应用
     */
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if ((currentTime - lastTime) < 2 * 1000) {
            //掉下面这个方法，就直接finish了
            super.onBackPressed();
        } else {
            ToastUtil.toast("请再按一次");
            lastTime = currentTime;
        }
    }

    private void initView() {
        mChoice = findViewByIdExt(R.id.main_tool_choice);
        mRoom = findViewByIdExt(R.id.main_tool_room);
        mProfile = findViewByIdExt(R.id.main_tool_profile);

        mChoice.setOnClickListener(this);
        mRoom.setOnClickListener(this);
        mProfile.setOnClickListener(this);
        mFragmentManager = getSupportFragmentManager();
        onTabSelected(FLAG_TAB_ONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_tool_choice:
                onTabSelected(FLAG_TAB_ONE);
                break;
            case R.id.main_tool_room:
                onTabSelected(FLAG_TAB_TWO);
                break;
            case R.id.main_tool_profile:
                onTabSelected(FLAG_TAB_THREE);
                break;
        }
    }

    /**
     * 选择tab
     */
    private void onTabSelected(int tabIndex) {
        if (tabIndex == preTabIndex) {
            if (tabIndex == FLAG_TAB_ONE) {
                mChoiceFragment.onTabDoubleClick();
            } else if (tabIndex == FLAG_TAB_TWO) {
                mLedimRoomFragment.onTabDoubleClick();
            }
        } else {
            if (tabIndex == FLAG_TAB_ONE) {
                mTransaction = mFragmentManager.beginTransaction();
                hideFragments(mTransaction);
                if (mChoiceFragment == null) {
                    mChoiceFragment = new LedimChoiceFragment();
                    mTransaction.add(R.id.main_fragment_container, mChoiceFragment);
                } else {
                    mTransaction.show(mChoiceFragment);
                }
                mTransaction.commit();
                mChoice.setSelected(true);
                mRoom.setSelected(false);
                mProfile.setSelected(false);
            } else if (tabIndex == FLAG_TAB_TWO) {
                mTransaction = mFragmentManager.beginTransaction();
                hideFragments(mTransaction);
                if (mLedimRoomFragment == null) {
                    mLedimRoomFragment = new LedimRoomFragment();
                    mTransaction.add(R.id.main_fragment_container, mLedimRoomFragment);
                } else {
                    mTransaction.show(mLedimRoomFragment);
                }
                mTransaction.commit();
                mChoice.setSelected(false);
                mRoom.setSelected(true);
                mProfile.setSelected(false);
            } else if (tabIndex == FLAG_TAB_THREE) {
                mTransaction = mFragmentManager.beginTransaction();
                hideFragments(mTransaction);
                if (mLedimProfileFragment == null) {
                    mLedimProfileFragment = new LedimProfileFragment();
                    mTransaction.add(R.id.main_fragment_container, mLedimProfileFragment);
                } else {
                    mTransaction.show(mLedimProfileFragment);
                }
                mTransaction.commit();
                mChoice.setSelected(false);
                mRoom.setSelected(false);
                mProfile.setSelected(true);
            }
        }
        preTabIndex = tabIndex;
    }

    /**
     * 隐藏tab
     */
    private void hideFragments(FragmentTransaction transaction) {
        if (mChoiceFragment != null) {
            transaction.hide(mChoiceFragment);
        }
        if (mLedimRoomFragment != null) {
            transaction.hide(mLedimRoomFragment);
        }
        if (mLedimProfileFragment != null) {
            transaction.hide(mLedimProfileFragment);
        }
    }

    public interface DoubleTabClickLister {

        void onTabDoubleClick();
    }
}
